# -*- coding: utf-8 -*-
from db_conn import *
import re
import time
import traceback
from warnings import filterwarnings

filterwarnings('error', category=MySQLdb.Warning)


def import_txt(arquivo_import):
    try:
        cursor,conn = db_connect()
        count_ln=0
        
        #field_names = {}
        #for i in range(len(cursor.description)):
        #    field_names[cursor.description[i][0]]=i-1
        #print field_names     
        field_names = ['TransmissaoInicial',
                         'UnidadeFrequenciaTX',
                         'RecepcaoInicial',
                         'UnidadeFrequenciaRX',
                         'Situacao',
                         'CaraterSecundario',
                         'IndConfidencial',
                         'TipoClasseEstacao',
                         'Horarios',
                         'DesignacaoEmissao',
                         'PotenciaOperacao',
                         'UnidadePotencia',
                         'Equipamento',
                         'TipoAntena',
                         'EquipamentoAntena',
                         'Ganho',
                         'FrenteCosta',
                         'AnguloMeiaPotencia',
                         'AnguloElevacao',
                         'Azimute',
                         'VariacaoAzimutal',
                         'TipoPolarizacao',
                         'Altura',
                         'Raio',
                         'Latitude',
                         'Longitude',
                         'Altitude',
                         'Estacao',
                         'Servico',
                         'Indicativo',
                         'MedPotenciaMaxima_TR',
                         'MedLarguraBanda',
                         'DiametroSGCH',
                         'Diagrama',
                         'SiglaEstacao_TRS',
                         'LongitudeOrbitalSubida',
                         'NomeFeixeSubida',
                         'SiglaEstacaoDescida',
                         'LongitudeOrbitalDescida',
                         'NomeFeixeDescida',
                         'TipoEstacao',
                         'NomeEntidade',
                         'NumEntidade',
                         'NomeMunicipio',
                         'CodMunicipio',
                         'Endereco',
                         'UF',
                         'TipoClasseCorrespondencia',
                         'Rede',
                         'Distancia',]
        dict_fields={}        
        for f in range(len(field_names)):
            dict_fields[field_names[f]]=f
        with open(arquivo_import) as infile:
            for line in infile:
                insert_values = ""
                for col in line.replace("\r","").replace("\n","").split("|"):
                    #insert_values += """'%s',""" % (re.escape(col))
                    #insert_values += """'%s',""" % (str(MySQLdb.escape_string(col)))
                    if len(str(MySQLdb.escape_string(col)))>0:
                        insert_values += ",'%s'" % (str(MySQLdb.escape_string(col)))
                    else:
                        insert_values += ',NULL'
                                            
                insert_anatel="""
                insert into anatel_import
                values(NULL%s,'%s',NULL);
                """ % (insert_values,arquivo_import)
                                
                try:
                    #print insert_anatel
                    cursor.execute(insert_anatel)
                except MySQLdb.Warning, e:
                    # handle warnings, if the cursor you're using raises them
                    arr_campo = re.findall("'([^']*)'", str(e));
                    print arr_campo[-1]
                    #print insert_anatel
                    #print col[field_names[arr_campo[0].replace("'","")]]
                    print arr_campo[-1] + ' "' + line.split("|")[int(dict_fields[arr_campo[-1].replace("'","")])] + '"'    
                    continue                
                except:
                    print "Erro ao atualizar o banco"
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                                      limit=2, file=sys.stdout)
                    
                count_ln+=1
                if count_ln%1000==0:
                    print "Counter: %s" % (count_ln)
        db_disconnect(cursor,conn)
    except:
        print "Erro ao atualizar o banco"
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)
        
def deleteAll():
    try:
        cursor,conn = db_connect()
        cursor.execute('DELETE FROM anatel_import;')
        cursor.execute('ALTER TABLE `anatel_import` AUTO_INCREMENT=0;')
        cursor.execute('DELETE FROM anatel_real;')
        cursor.execute('DELETE FROM anatel_atualizacoes;')     
        cursor.execute('ALTER TABLE `anatel_atualizacoes` AUTO_INCREMENT=0;')
        cursor.execute('DELETE FROM anatel_enlaces;')  
        cursor.execute('DELETE FROM anatel_double_check;')
        db_disconnect(cursor,conn)
    except:
        print "Erro ao apagar!"    


if __name__ == '__main__':
    if not len(sys.argv) < 2:
        
        for v in sys.argv:
            if len(v.split("="))>1:
                param = v.split("=")[0].strip()
                valor = v.split("=")[1].strip()
                try:
                    if param.lower().strip().find("arquivo_import")>-1:
                        arquivo_import = valor
                        print "arquivo_import: %s" % (arquivo_import)
                    elif param.lower().strip().find("delete")>-1:
                        delete = int(valor)
                        print "delete: %s" % (delete)                                                      
                    else:
                        eval('%s=%s' % (param,valor))   
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "%s:%s" % (exceptionType,exceptionValue)
    
    
    start_total = time.time()
    
    print "(Comecando!)"
    
    if delete:
        print "Apagando..."
        deleteAll()    
        print "Fim delete..."
        
    print "Iniciando import arquivo: %s" % (arquivo_import)
    import_txt(arquivo_import)
    print "Fim import!"
    
    print "(Total Tempo Gasto: %s)" % ((time.time() - start_total))
    